package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.R;
import com.example.demo.dto.UserDto;
import com.example.demo.entity.Map;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.LoginService;
import com.example.demo.service.MapService;
import com.example.demo.service.UserService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
@CrossOrigin(origins = "*", maxAge = 3600)
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MapService mapService;


    /**
     * 加密
     */
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 用户信息分页查询, 需要admin权限
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    @PreAuthorize("hasAuthority('admin')") //用户权限
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page = {},pageSize = {},name = {}", page, pageSize, name);

        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), User::getUserName, name);
        //添加排序条件
        queryWrapper.orderByDesc(User::getUpdateTime);

        //执行查询
        userService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * 根据ID修改用户信息
     *
     * @param user
     * @return
     */
    @PatchMapping
    @Transactional
    public R<String> update(@RequestBody User user) {
        log.info("根据id修改用户信息..." + user.toString());

        // long id = Thread.currentThread().getId();
        // log.info("线程id为：{}",id);
        // 这块可以写成如果是用户自己更新没事 , 管理员更新的话可以来整一整 , 当然还需要新增字段
        // Long userId = (Long)request.getSession().getAttribute("user");
        // user.setUpdateTime(LocalDateTime.now());
        //HmacSHA256进行加密
        if (user.getUserPassword() != null) {
            String password = user.getUserPassword();
            String encode = passwordEncoder.encode(password);
            user.setUserPassword(encode);
        }

        userService.updateById(user);

        // 更新省份 , 人数有差 , 不完善这个功能了,完善了感觉不太好 , 人数展示越多越好
        if (user.getUserAddress() != null) {
            Map map = new Map();
            map.setName(user.getUserAddress());
            mapService.updateMap(map);
        }


        return R.success("用户信息修改成功");
    }

    /**
     * 根据ID查询用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<User> getById(@PathVariable Long id) {
        log.info("根据id查询用户信息...");
        User user = userService.getById(id);
        if (user != null) {
            user.setUserPassword("******");
            return R.success(user);
        }
        return R.error("没有查询到对应用户信息");
    }

    // @Test
    @RequestMapping("/hello")
    public R<List<User>> hello() {
        List<User> users = userMapper.selectAll();
        System.out.println(users);
        return R.success(users);
    }

    @GetMapping("/getID")
    public R<User> hello(Long id) {
        User userInfo = userMapper.getUserInfo(id);
        System.out.println(userInfo);
        return R.success(userInfo);
    }


    /**
     * 查到相似用户
     * @param size
     * @param id
     * @return
     */
    @GetMapping("/match")
    public R<List<User>> match(int size,Long id){

        //查询几个和当前用户ID
        List<User> userList = userService.matchUsers(size, id);

        return R.success(userList);
    }
}
